package mutsumimod.vfx;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.helpers.ImageMaster;
import com.megacrit.cardcrawl.vfx.AbstractGameEffect;

public class WhiteMoonEffect extends AbstractGameEffect {
    private final AbstractCreature target;
    private float fadeInTimer;
    private float fadeOutTimer = -1;
    private boolean hasPlayedSound = false;

    // 阶段控制常量
    private static final float FADE_IN_DURATION = 1.5f;
    private static final float FADE_OUT_DURATION = 1.0f;

    public WhiteMoonEffect(AbstractCreature target) {
        this.target = target;
        this.duration = 9999.0f; // 设置超长持续时间，通过逻辑控制实际结束
        this.color = new Color(1.0f, 1.0f, 0.8f, 0.0f);
        this.fadeInTimer = FADE_IN_DURATION;
    }

    public void update() {
        // 渐出阶段优先处理
        if (fadeOutTimer >= 0) {
            fadeOutTimer -= Gdx.graphics.getDeltaTime();

            // 计算渐出透明度（线性插值）
            this.color.a = Interpolation.linear.apply(
                    0.5f,
                    0.0f,
                    1 - (fadeOutTimer / FADE_OUT_DURATION)
            );

            if (fadeOutTimer <= 0) {
                this.isDone = true;
            }
            return;
        }

        // 渐入阶段处理
        if (fadeInTimer > 0) {
            // 首次进入时播放音效
            if (!hasPlayedSound) {
                CardCrawlGame.sound.playA("INTIMIDATE", -0.6f);
                hasPlayedSound = true;
            }

            fadeInTimer -= Gdx.graphics.getDeltaTime();
            float progress = 1 - (fadeInTimer / FADE_IN_DURATION);

            // 使用exp10In插值实现渐入效果
            this.color.a = Interpolation.exp10In.apply(
                    0.0f,
                    0.5f,
                    progress
            );
        }
        // 保持阶段（透明度保持0.5）
        else {
            this.color.a = 0.5f;
        }
    }

    // 新增的关闭方法
    public void close() {
        if (fadeOutTimer < 0) { // 防止重复触发
            fadeOutTimer = FADE_OUT_DURATION;
        }
    }

    public void render(SpriteBatch sb) {
        sb.setColor(this.color);
        sb.setBlendFunction(770, 1);

        if (!target.isDead && !target.isDying) {
            float fixedWidth = 500.0f * Settings.scale;
            float fixedHeight = 1800.0f * Settings.scale;

            sb.draw(ImageMaster.SPOTLIGHT_VFX,
                    target.drawX - fixedWidth / 2.0f,
                    target.drawY - fixedHeight / 2.0f,
                    fixedWidth,
                    fixedHeight);
        }

        sb.setBlendFunction(770, 771);
    }

    public void dispose() {
        // 可选：如果需要释放资源可在此添加
    }
}